<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="优惠券名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入优惠券名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:coupon:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:coupon:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:coupon:remove']"
        >删除</el-button>
      </el-col>
<!--      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:coupon:export']"
        >导出</el-button>
      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="couponList" border size="mini" stripe @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键id" align="center" prop="id" v-if="false"/>
      <el-table-column label="优惠券名称" align="center" prop="title" />
      <el-table-column label="描述" align="center" prop="description" />
      <el-table-column label="总数量" align="center" prop="total" />
      <el-table-column label="剩余数量" align="center" prop="surplus" />
      <el-table-column label="可领取" align="center" prop="limitNum" />
      <el-table-column label="面额" align="center" prop="discount"  >
        <template slot-scope="scope">
          <span >{{ scope.row.discount/100}}</span>
        </template>
      </el-table-column>
      <el-table-column label="使用限制" align="center" prop="isType" >
        <template slot-scope="scope">
          <span v-if="scope.row.isType==0">未设置</span>
          <span v-else-if="scope.row.isType==1">消费满{{scope.row.max/100}}元减</span>
          <span v-else>最低消费{{ scope.row.min/100}} 元减</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="使用类型" align="center" prop="courseName" />
      <el-table-column label="过期天数" align="center" prop="days" />
      <el-table-column label="可领取时间" align="center" prop="gmtStart" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtStart, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束领取时间" align="center" prop="gmtEnd" width="135">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.gmtEnd, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:coupon:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:coupon:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改优惠券管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="40%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules"   label-width="120px">
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入优惠券名称" />
        </el-form-item>
        <el-form-item label="抵用金额" prop="discount">
          <el-input v-model="form.discount" placeholder="请输入抵用金额" />
        </el-form-item>
        <el-form-item label="优惠券分类" prop="courseId">
          <el-select v-model="form.courseId" clearable filterable  placeholder="优惠券分类" style="width: 100%">
            <el-option
              v-for="dict in allClassListOption"
              :key="dict.id"
              :label="dict.title"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商户电话" prop="phone" v-if="form.courseId == 3 ">
          <el-input v-model="form.phone" placeholder="请输入商户电话" />
        </el-form-item>
        <el-form-item label="选择停车场" prop="parkCode" v-if="form.courseId == 3 ">
          <el-select v-model="form.parkCode" style="width: 100%"  placeholder="请选择所属停车场" filterable clearable size="small" >
            <el-option
              v-for="park in parkListOptions"
              :key="park.parkCode"
              :label="park.parkName"
              :value="park.parkCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="使用类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择使用类型，如满减"  style="width: 100%">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="使用限制" prop="isType">
          <el-select v-model="form.isType" placeholder="请选择使用限制"  style="width: 100%">
            <el-option
              v-for="dict in isTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="满多少减" prop="max" v-if="form.isType == 1" >
          <el-input-number :min="0" v-model="form.max" placeholder="请输入满多少减"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="最低消费金额" prop="min"  v-if="form.isType == 2">
          <el-input-number :min="0" v-model="form.min" placeholder="请输入最低消费金额"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="总数量" prop="total">
          <el-input-number :min="0" v-model="form.total" placeholder="请输入总数量"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="可领取" prop="limitNum">
          <el-input-number :min="1" v-model="form.limitNum" placeholder="请输入可领取优惠券张数"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="过期天数" prop="days">
          <el-input-number v-model="form.days" :min="0" placeholder="请输入过期天数"  style="width: 100%"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="领取开始时间" prop="gmtStart">
          <el-date-picker clearable size="small"
            v-model="form.gmtStart"
            type="datetime"  style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择领取开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="领取结束时间" prop="gmtEnd">
          <el-date-picker clearable size="small"
            v-model="form.gmtEnd"
            type="datetime"  style="width: 100%"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="选择领取结束时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/system/coupon";
import {allClassList } from "@/api/system/course";
import { getParkList} from "@/api/system/park";
export default {
  name: "Coupon",
  components: {
  },
  data() {
    return {
	  //按钮loading
	  buttonLoading: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券管理表格数据
      couponList: [],
      // 停车场列表
      parkListOptions: [],
      // 弹出层优惠券名称
      title: "",
      // 是否显示弹出层
      open: false,
      // 使用类型，如满减字典
      typeOptions: [],
      //所有分类下拉列表
      allClassListOption: [],
      // 状态0冻结，1激活字典
      statusOptions: [],
      // 使用限制字典
      isTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "使用类型不能为空", trigger: "blur" }
        ],
        total: [
          { required: true, message: "总数量不能为空", trigger: "blur" }
        ],
        discount: [
          { required: true, message: "面额不能为空", trigger: "blur" }
        ],
        isType: [
          { required: true, message: "使用限制不能为空", trigger: "blur" }
        ],
        phone: [
          {  message: "请输入正确的商户手机号", trigger: "blur",pattern: /^1[3456789]\d{9}$/ }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.allClassList();
    this.getParkList();
    this.getDicts("coupon_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts("coupon_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("coupon_is_type").then(response => {
      this.isTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询优惠券管理列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询优惠券管理列表 */
    allClassList() {
      let data = {}
      allClassList(data).then(response => {
        this.allClassListOption = response.data;
      });
    },
    getParkList(){
      let data={}
      getParkList(data).then(response => {
        this.parkListOptions = response.data;
      });
    },
    // 使用类型，如满减字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 状态0冻结，1激活字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 使用限制字典翻译
    isTypeFormat(row, column) {
      return this.selectDictLabel(this.isTypeOptions, row.isType);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        title: undefined,
        type: undefined,
        description: undefined,
        total: 1,
        discount: undefined,
        min: 0,
        max: 0,
        status: 0,
        courseId: undefined,
        isType: undefined,
        days: undefined,
        userId: undefined,
        gmtStart: undefined,
        gmtEnd: undefined,
        url: undefined,
        parkCode: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCoupon(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.form.min = this.form.min / 100;
        this.form.max = this.form.max / 100;
        this.form.discount = this.form.discount / 100;
        this.open = true;
        this.title = "修改优惠券管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (this.compareTime(this.form.gmtStart,this.form.gmtEnd) == false){
          this.msgError("请选择正确的时间段");
          return false;
        }
        this.form.min = this.form.min * 100;
        this.form.max = this.form.max * 100;
        this.form.discount = this.form.discount * 100;
        if (valid) {
          this.buttonLoading = true;
          if (this.form.id != null) {
            updateCoupon(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then(response => {
              this.buttonLoading = false;
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除优惠券管理编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delCoupon(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠券管理数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
